<?php

namespace plugin\cms\app\controller\home;

use core\controller\HomeBase;
use Exception;
use plugin\cms\app\bll\Category as BllCategory;
use plugin\cms\app\bll\Content as BllContent;
use support\View;

class Index extends HomeBase
{
    public function index()
    {
        return $this->view();
    }

    public function category()
    {
        $cid = request()->get('cid');
        $bllCategory = new BllCategory();
        $cateinfo = $bllCategory->find($cid, now_site()['id']);
        View::assign('cateinfo', $cateinfo);
        return $this->view($cateinfo['catetemp']);
    }
    public function page()
    {
        $cid         = request()->get('cid');
        $bllCategory = new BllCategory();
        $cateinfo    = $bllCategory->find($cid, now_site()['id']);


        $bllContent = new BllContent();
        $content = $bllContent->find(
            request()->get('id'),
            request()->get('cid'),
            now_site()['id']
        );

        //增加浏览次数
        $bllContent->viewCountIncrement(
            request()->get('id'),
            request()->get('cid'),
            now_site()['id']
        );



        View::assign('content', $content);
        return $this->view($cateinfo['pagetemp']);
    }


    /**
     * 下载
     * 
     *
     * @return mixed
     */
    public function download()
    {
        //cid id field idx 通过栏目ID  文章id 下载字段 文件索引

        $getdata = request()->get();
        $bllContent = new BllContent();
        $content = $bllContent->find(
            $getdata['id'],
            $getdata['cid'],
            now_site()['id']
        );

        if (!$content) {
            throw new Exception('内容不存在');
        }

        if (!isset($content[$getdata['field']])) {
            throw new Exception('文件不存在');
        }

        // 判断是否有下载权限
        $canview = $bllContent->userCanViewContent(
            uid: is_login() ? get_login_user()['id'] : 0,
            id: $getdata['id'],
            cid: $getdata['cid'],
            siteid: now_site()['id']
        );

        if (!$canview) {
            return $this->error('无权限');
        }

        if (!is_json($content[$getdata['field']])) {
            return response()->download(
                public_path()  . $content[$getdata['field']],
                isset($getdata['name']) ? $getdata['name'] : ''
            );
        }

        $files = json_decode($content[$getdata['field']], true);

        return response()->download(
            public_path() . $files[$getdata['idx']]['path'],
            isset($getdata['name']) ? $files[$getdata['idx']][$getdata['name']] : ''
        );
    }


    public function search()
    {
        return $this->view();
    }
}
